var util = require('./util');
var wrapper = util.wrapper;
var postJSON = util.postJSON;
var path = require('path');
var fs = require('fs');
var formstream = require('formstream');

/**
 * 获取客服聊天记录
 * 详细请看：http://mp.weixin.qq.com/wiki/19/7c129ec71ddfa60923ea9334557e8b23.html
 *
 * Opts:
 * ```
 * {
 *  "starttime" : 123456789,
 *  "endtime" : 987654321,
 *  "openid": "OPENID", // 非必须
 *  "pagesize" : 10,
 *  "pageindex" : 1,
 * }
 * ```
 * Examples:
 * ```
 * api.getRecords(opts, callback);
 * ```
 * Callback:
 *
 * - `err`, 调用失败时得到的异常
 * - `result`, 调用正常时得到的对象
 *
 * Result:
 * ```
 * {
 *  "recordlist": [
 *    {
 *      "worker": " test1",
 *      "openid": "oDF3iY9WMaswOPWjCIp_f3Bnpljk",
 *      "opercode": 2002,
 *      "time": 1400563710,
 *      "text": " 您好，客服test1为您服务。"
 *    },
 *    {
 *      "worker": " test1",
 *      "openid": "oDF3iY9WMaswOPWjCIp_f3Bnpljk",
 *      "opercode": 2003,
 *      "time": 1400563731,
 *      "text": " 你好，有什么事情？ "
 *    },
 *  ]
 * }
 * ```
 * @param {Object} opts 查询条件
 * @param {Function} callback 回调函数
 */
exports.getRecords = function (opts, callback) {
  this.preRequest(this._getRecords, arguments);
};

/*!
 * 获取客服聊天记录的未封装版本
 */
exports._getRecords = function (opts, callback) {
  // https://api.weixin.qq.com/customservice/msgrecord/getrecord?access_token=ACCESS_TOKEN
  var url = this.customservicePrefix + 'msgrecord/getrecord?access_token=' + this.token.accessToken;
  this.request(url, postJSON(opts), wrapper(callback));
};

/**
 * 获取客服基本信息
 * 详细请看：http://dkf.qq.com/document-3_1.html
 *
 * Examples:
 * ```
 * api.getCustomServiceList(callback);
 * ```
 * Callback:
 *
 * - `err`, 调用失败时得到的异常
 * - `result`, 调用正常时得到的对象
 *
 * Result:
 * ```
 * {
 *   "kf_list": [
 *     {
 *       "kf_account": "test1@test",
 *       "kf_nick": "ntest1",
 *       "kf_id": "1001"
 *     },
 *     {
 *       "kf_account": "test2@test",
 *       "kf_nick": "ntest2",
 *       "kf_id": "1002"
 *     },
 *     {
 *       "kf_account": "test3@test",
 *       "kf_nick": "ntest3",
 *       "kf_id": "1003"
 *     }
 *   ]
 * }
 * ```
 * @param {Function} callback 回调函数
 */
exports.getCustomServiceList = function (callback) {
  this.preRequest(this._getCustomServiceList, arguments);
};

/*!
 * 获取客服基本信息的未封装版本
 */
exports._getCustomServiceList = function (callback) {
  // https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token= ACCESS_TOKEN
  var url = this.prefix + 'customservice/getkflist?access_token=' + this.token.accessToken;
  this.request(url, {dataType: 'json'}, wrapper(callback));
};

/**
 * 获取在线客服接待信息
 * 详细请看：http://dkf.qq.com/document-3_2.html
 *
 * Examples:
 * ```
 * api.getOnlineCustomServiceList(callback);
 * ```
 *
 * Callback:
 *
 * - `err`, 调用失败时得到的异常
 * - `result`, 调用正常时得到的对象
 *
 * Result:
 * ```
 * {
 *   "kf_online_list": [
 *     {
 *       "kf_account": "test1@test",
 *       "status": 1,
 *       "kf_id": "1001",
 *       "auto_accept": 0,
 *       "accepted_case": 1
 *     },
 *     {
 *       "kf_account": "test2@test",
 *       "status": 1,
 *       "kf_id": "1002",
 *       "auto_accept": 0,
 *       "accepted_case": 2
 *     }
 *   ]
 * }
 * ```
 * @param {Function} callback 回调函数
 */
exports.getOnlineCustomServiceList = function (callback) {
  this.preRequest(this._getOnlineCustomServiceList, arguments);
};

/*!
 * 获取在线客服接待信息的未封装版本
 */
exports._getOnlineCustomServiceList = function (callback) {
  // https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token= ACCESS_TOKEN
  var url = this.prefix + 'customservice/getonlinekflist?access_token=' + this.token.accessToken;
  this.request(url, {dataType: 'json'}, wrapper(callback));
};

/**
 * 添加客服账号
 * 详细请看：http://mp.weixin.qq.com/wiki/9/6fff6f191ef92c126b043ada035cc935.html
 *
 * Examples:
 * ```
 * api.addKfAccount('test@test', 'nickname', 'password', callback);
 * ```
 *
 * Callback:
 *
 * - `err`, 调用失败时得到的异常
 * - `result`, 调用正常时得到的对象
 *
 * Result:
 * ```
 * {
 *  "errcode" : 0,
 *  "errmsg" : "ok",
 * }
 * ```
 * @param {String} account 账号名字，格式为：前缀@公共号名字
 * @param {String} nick 昵称
 * @param {String} password 密码，可以直接传递明文，wechat模块自动进行md5加密
 * @param {Function} callback 回调函数
 */
exports.addKfAccount = function (account, nick, password, callback) {
  this.preRequest(this._addKfAccount, arguments);
};

var md5 = function (input) {
  var crypto = require('crypto');
  var hash = crypto.createHash('md5');
  return hash.update(input).digest('hex');
};

/*!
 * 添加客服账号的未封装版本
 */
exports._addKfAccount = function (account, nick, password, callback) {
  // https://api.weixin.qq.com/customservice/kfaccount/add?access_token=ACCESS_TOKEN
  var prefix = 'https://api.weixin.qq.com/';
  var url = prefix + 'customservice/kfaccount/add?access_token=' + this.token.accessToken;
  var data = {
    "kf_account": account,
    "nickname": nick,
    "password": md5(password),
  };

  this.request(url, postJSON(data), wrapper(callback));
};

/**
 * 设置客服账号
 * 详细请看：http://mp.weixin.qq.com/wiki/9/6fff6f191ef92c126b043ada035cc935.html
 *
 * Examples:
 * ```
 * api.updateKfAccount('test@test', 'nickname', 'password', callback);
 * ```
 *
 * Callback:
 *
 * - `err`, 调用失败时得到的异常
 * - `result`, 调用正常时得到的对象
 *
 * Result:
 * ```
 * {
 *  "errcode" : 0,
 *  "errmsg" : "ok",
 * }
 * ```
 * @param {String} account 账号名字，格式为：前缀@公共号名字
 * @param {String} nick 昵称
 * @param {String} password 密码，可以直接传递明文，wechat模块自动进行md5加密
 * @param {Function} callback 回调函数
 */
exports.updateKfAccount = function (account, nick, password, callback) {
  this.preRequest(this._updateKfAccount, arguments);
};

/*!
 * 设置客服账号的未封装版本
 */
exports._updateKfAccount = function (account, nick, password, callback) {
  // https://api.weixin.qq.com/customservice/kfaccount/add?access_token=ACCESS_TOKEN
  var prefix = 'https://api.weixin.qq.com/';
  var url = prefix + 'customservice/kfaccount/update?access_token=' + this.token.accessToken;
  var data = {
    "kf_account": account,
    "nickname": nick,
    "password": md5(password),
  };

  this.request(url, postJSON(data), wrapper(callback));
};

/**
 * 删除客服账号
 * 详细请看：http://mp.weixin.qq.com/wiki/9/6fff6f191ef92c126b043ada035cc935.html
 *
 * Examples:
 * ```
 * api.deleteKfAccount('test@test', callback);
 * ```
 *
 * Callback:
 *
 * - `err`, 调用失败时得到的异常
 * - `result`, 调用正常时得到的对象
 *
 * Result:
 * ```
 * {
 *  "errcode" : 0,
 *  "errmsg" : "ok",
 * }
 * ```
 * @param {String} account 账号名字，格式为：前缀@公共号名字
 * @param {Function} callback 回调函数
 */
exports.deleteKfAccount = function (account, callback) {
  this.preRequest(this._deleteKfAccount, arguments);
};

/*!
 * 删除客服账号的未封装版本
 */
exports._deleteKfAccount = function (account, callback) {
  // https://api.weixin.qq.com/customservice/kfaccount/del?access_token=ACCESS_TOKEN
  var prefix = 'https://api.weixin.qq.com/';
  var url = prefix + 'customservice/kfaccount/del?access_token=' + this.token.accessToken + '&kf_account=' + account;

  this.request(url, {dataType: 'json'}, wrapper(callback));
};

/**
 * 设置客服头像
 * 详细请看：http://mp.weixin.qq.com/wiki/9/6fff6f191ef92c126b043ada035cc935.html
 *
 * Examples:
 * ```
 * api.setKfAccountAvatar('test@test', '/path/to/avatar.png', callback);
 * ```
 *
 * Callback:
 *
 * - `err`, 调用失败时得到的异常
 * - `result`, 调用正常时得到的对象
 *
 * Result:
 * ```
 * {
 *  "errcode" : 0,
 *  "errmsg" : "ok",
 * }
 * ```
 * @param {String} account 账号名字，格式为：前缀@公共号名字
 * @param {String} filepath 头像路径
 * @param {Function} callback 回调函数
 */
exports.setKfAccountAvatar = function (account, filepath, callback) {
  this.preRequest(this._setKfAccountAvatar, arguments);
};

/*!
 * 上传多媒体文件的未封装版本
 */
exports._setKfAccountAvatar = function (account, filepath, callback) {
  // http://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token=ACCESS_TOKEN&kf_account=KFACCOUNT
  var that = this;
  fs.stat(filepath, function (err, stat) {
    if (err) {
      return callback(err);
    }
    var form = formstream();
    form.file('media', filepath, path.basename(filepath), stat.size);
    var prefix = 'http://api.weixin.qq.com/';
    var url = prefix + 'customservice/kfaccount/uploadheadimg?access_token=' + that.token.accessToken + '&kf_account=' + account;
    var opts = {
      dataType: 'json',
      type: 'POST',
      timeout: 60000, // 60秒超时
      headers: form.headers(),
      stream: form
    };
    that.request(url, opts, wrapper(callback));
  });
};
